package com.qingfeng.manager.service;

import com.github.pagehelper.PageInfo;
import com.qingfeng.core.config.database.ReadOnlyConnection;
import com.qingfeng.core.dao.PermissionDao;
import com.qingfeng.core.entity.Permission;
import com.qingfeng.core.entity.Userinfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description:
 * @author:LWY
 * @date: 2017/10/16 17:26
 * @modified:
 */
@Service
public class PermissionService {


    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    RoleService roleService;


    /**
     * 查询所有的权限
     *
     * @return
     */
    @ReadOnlyConnection
    public PageInfo<Permission> get() {
        return permissionDao.get(0, 0, null);
    }


    /**
     * 查询角色所有的权限
     *
     * @param role_id 角色id
     * @return
     */
    @ReadOnlyConnection
    public Set<Permission> byRole(String role_id) {
        return permissionDao.byRole(role_id);
    }

    /**
     * 根据权限菜单类型和用户获取权限菜单
     *
     * @param permission_type 类型（0：菜单，1：按钮）
     * @return
     */
    @ReadOnlyConnection
    public List<Permission> byTypeAndUserinfo(Integer permission_type) {
        //获得当前用户
        Userinfo userinfo = (Userinfo) SecurityUtils.getSubject().getPrincipal();
        return permissionDao.byTypeAndUserinfo(permission_type, userinfo.getId());
    }

    /**
     * 根据父菜单和用户获取权限按钮
     *
     * @param p_id 父菜单id
     * @return
     */
    public List<Permission> getButtonByPidAndUserinfo(String p_id) {
        //获得当前用户
        Userinfo userinfo = (Userinfo) SecurityUtils.getSubject().getPrincipal();
        return permissionDao.getButtonByPidAndUserinfo(p_id, userinfo.getId());
    }

    /**
     * 保存
     *
     * @param p_id             父节点id
     * @param permission_name  权限名称
     * @param icon_url         icon_url
     * @param permission_type  权限类型
     * @param url              url
     * @param permission_order 顺序
     * @return
     */
    public Permission save(String id, String p_id, String permission_name, String icon_url, String permission_type, String url, String method, String permission_order) {
        //获得当前用户
        Userinfo userinfo = (Userinfo) SecurityUtils.getSubject().getPrincipal();
        return permissionDao.save(id, p_id, permission_name, icon_url, permission_type, url, method, permission_order, userinfo.getId());
    }

    @Transactional
    public void del(String[] ids) {
        permissionDao.del(ids);
    }

    public Permission get(String id) {
        return permissionDao.byId(id);
    }

    /**
     * 获取所有权限并且标记某角色有哪些权限
     *
     * @param role_id
     * @return
     */
    public List<Map> forRole(String role_id) {
        return permissionDao.forRole(role_id);
    }
}
